package com.zf.spring.microservice.service.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.CharsetUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServerHandler extends SimpleChannelInboundHandler<Object> {
	private static final Logger logger = LoggerFactory
			.getLogger(NettyServerHandler.class);
	Map<String, List<String>> requestData = new HashMap<String, List<String>>();

	public NettyServerHandler() {
		super();
		logger.debug("********************");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		logger.debug("read0000000000000000000000000000000");
		if (msg instanceof HttpRequest) {
			HttpRequest request = (HttpRequest) msg;

			QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
					request.uri());
			requestData = new HashMap<String, List<String>>(queryStringDecoder.parameters());
			// IP
			String[] ip = ChannelUtil.getIpAddress(ctx, request);
			List<String> asList = Arrays.asList(ip);
			requestData.put("remoteAddr",asList);
		}

		// 获取body内的参数
		if (msg instanceof HttpContent) {
			String data = null;
			HttpContent httpContent = (HttpContent) msg;

			ByteBuf content = httpContent.content();
			if (content.isReadable()) {
				data = content.toString(CharsetUtil.UTF_8);
			}
			if (data != null) {
				requestData.put("httpBody", Arrays.asList(data));
			}

		}
		if(msg instanceof LastHttpContent){
			NettyRunner.cachedThreadPool.execute(new OperIntegralExecutor(ctx,
					requestData));
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.warn("处理异常" + cause.getMessage(), cause);
		ChannelUtil.writeResponseMessage(
				new ResponseMessage(false, cause.getMessage()), ctx, null);
	}

}
